<template>
  <ContentWrap>
    <el-row :gutter="20">
      <el-col :span="4">
        <el-form-item>
          <el-button @click="submitForm" type="primary" :disabled="formLoading" v-hasPermi="['wms:rdrecord07:create']" v-if="vIf('create')">提 交</el-button>
          <el-button @click="updateForm" type="primary" :disabled="formLoading" v-hasPermi="['wms:rdrecord07:update']" v-if="vIf('view')">修 改</el-button>
          <el-button @click="submitForm" type="primary" :disabled="formLoading" v-hasPermi="['wms:rdrecord07:update']" v-if="vIf('update')">保 存</el-button>
          <el-button @click="updateForm" :disabled="formLoading" v-if="vIf('update')">取 消</el-button>
        </el-form-item>
      </el-col>
    </el-row>
    <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" v-loading="formLoading">
      <el-row :gutter="20">
        <el-form-item label="流水号" prop="serialNumber">
          <el-input v-model="formData.serialNumber" placeholder="保存自动生成" :disabled="true" />
        </el-form-item>
        <el-form-item label="业务员" prop="personId">
          <el-select v-model="formData.personId" @change="personChange"
                     clearable filterable placeholder="请选择业务员" :disabled="isDisabled()" class="!w-192px">
            <el-option v-for="item in personList" :key="item.id" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="部门" prop="deptId">
          <el-select v-model="formData.deptId" placeholder="" :disabled="true" class="!w-192px">
            <el-option v-for="item in deptList" :key="item.id" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="调出仓库" prop="outWarehouseId">
          <el-select v-model="formData.outWarehouseId" clearable filterable placeholder="请选择仓库" :disabled="isDisabled()" class="!w-192px">
            <el-option v-for="item in warehouseList" :key="item.id" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="调入仓库" prop="inWarehouseId">
          <el-select v-model="formData.inWarehouseId" clearable filterable placeholder="请选择仓库" :disabled="isDisabled()" class="!w-192px">
            <el-option v-for="item in warehouseList" :key="item.id" :label="item.name" :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="单据日期" prop="orderDate">
          <el-date-picker v-model="formData.orderDate" type="date" value-format="x" placeholder="选择订单日期" :disabled="isDisabled()" class="!w-192px"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="formData.remark" placeholder="请输入备注" :disabled="isDisabled()" />
        </el-form-item>
      </el-row>
    </el-form>
    <!-- 子表的表单 -->
    <el-tabs v-model="subTabsName">
      <el-tab-pane label="调拨入库明细" name="rdrecords07">
        <Rdrecords07Form ref="rdrecords07FormRef" :order-id="formData.id" :out-warehouse-id="formData.outWarehouseId" />
      </el-tab-pane>
    </el-tabs>
    <el-row :gutter="20" class="mt-3">
      <el-col :span="0"/>
      <el-col :span="6">
        <el-form-item label="创建人" prop="creatorName">
          <el-input v-model="formData.creatorName" :disabled="true" />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="创建时间" prop="createTime">
          <el-date-picker v-model="formData.createTime" type="datetime" :disabled="true" />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="审核人" prop="auditorName">
          <el-input v-model="formData.auditorName" :disabled="true" />
        </el-form-item>
      </el-col>
      <el-col :span="6">
        <el-form-item label="审核时间" prop="auditTime">
          <el-date-picker v-model="formData.auditTime" type="datetime" :disabled="true" />
        </el-form-item>
      </el-col>
    </el-row>
  </ContentWrap>
</template>
<script setup lang="ts">
import { Rdrecord07Api, Rdrecord07VO } from '@/api/wms/rdrecord07'
import Rdrecords07Form from './components/Rdrecords07Form.vue'
import * as DeptApi from "@/api/system/dept";
import { PersonApi, PersonVO } from "@/api/wms/person";
import { WarehouseApi, WarehouseVO } from "@/api/wms/warehouse";
import { useRoute, useRouter } from 'vue-router';
import {unref} from "vue";
import { useTagsViewStore } from '@/store/modules/tagsView'
import bus from '@/utils/bus'

/** 调拨出库主 表单 */
defineOptions({ name: 'Rdrecord07Form' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改；view - 查看
const formData = ref({
  id: undefined,
  serialNumber: undefined,
  personId: undefined,
  deptId: undefined,
  inWarehouseId: undefined,
  outWarehouseId: undefined,
  orderDate: undefined,
  remark: undefined,
  auditor: undefined,
  auditTime: undefined,
})
const formRules = reactive({
  personId: [{ required: true, message: '业务员不能为空', trigger: 'blur' }],
  deptId: [{ required: true, message: '部门不能为空', trigger: 'blur' }],
  outWarehouseId: [{ required: true, message: '调出仓库不能为空', trigger: 'blur' }],
  inWarehouseId: [{ required: true, message: '调入仓库不能为空', trigger: 'blur' }],
  orderDate: [{ required: true, message: '单据日期不能为空', trigger: 'blur' }],
})
const route = useRoute();
const { currentRoute, push, router } = useRouter() // 路由
const tagsViewStore = useTagsViewStore()
const formRef = ref() // 表单 Ref
const personList = ref<PersonVO[]>([])
const deptList = ref<DeptApi.DeptVO[]>([])
const warehouseList =  ref<WarehouseVO[]>([])

/** 子表的表单 */
const subTabsName = ref('rdrecords07')
const rdrecords07FormRef = ref()

/** 加载数据 */
const init = async (type: string, id?: string) => {
  formType.value = type
  resetForm()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await Rdrecord07Api.getRdrecord07(id)
    } finally {
      formLoading.value = false
    }
  }
}

const personChange = (val) => {
  let person = personList.value.find(map => map.id === val)
  formData.value.deptId = person.deptId
}

/** 显示 */
const vIf = (type) => {
  if (route.query.type) {
    return route.query.type === type
  }
  return false
}

/** 权限 */
const isDisabled = () => {
  if (route.query.type) {
    return route.query.type === 'view'
  }
  return true
}

/** 修改表单 */
const updateForm = () => {
  if (route.query.type==='view') {
    push('/inventory/rdrecord07Form?type=update&id=' + route.query.id)
  } else {
    push('/inventory/rdrecord07Form?type=view&id=' + route.query.id)
  }
}

/** 提交表单 */
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 校验子表单
  try {
    await rdrecords07FormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'rdrecords07'
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as Rdrecord07VO
    // 拼接子表的数据
    data.rdrecords07s = rdrecords07FormRef.value.getData()
    if (formType.value === 'create') {
      await Rdrecord07Api.createRdrecord07(data)
      message.success(t('common.createSuccess'))
    } else {
      await Rdrecord07Api.updateRdrecord07(data)
      message.success(t('common.updateSuccess'))
    }
    // 发送操作成功的事件
    bus.emit('sendMsg', 'rdrecord07')
    tagsViewStore.delView(unref(currentRoute))
    await push('/inventory/rdrecord07')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    serialNumber: undefined,
    personId: undefined,
    deptId: undefined,
    inWarehouseId: undefined,
    outWarehouseId: undefined,
    orderDate: Date.parse(new Date()),
    remark: undefined,
    auditor: undefined,
    auditTime: undefined,
  }
  formRef.value?.resetFields()
}

/** 初始化 **/
onMounted(async () => {
  // 加载业务员
  personList.value = await PersonApi.getPersonSimpleList()
  // 加载部门
  deptList.value = await DeptApi.getSimpleDeptList()
  // 加载仓库
  warehouseList.value = await WarehouseApi.getWarehouseSimpleList()
  formType.value = route.query.type ? String(route.query.type) : 'view'
  if (route.query.id) {
    await init(formType.value, String(route.query.id))
  } else {
    await init('create')
  }
})
</script>
